package com.blackhorse.routing;

import com.blackhorse.utils.ConnectionUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 路由模式的交换机类型为：direct
 */
public class Producer {
    public static final String DIRECT_EXCHAGE = "direct_exchange";
    public static final String DIRECT_QUEUE_INSERT = "direct_queue_insert";
    public static final String DIRECT_QUEUE_UPDATE = "direct_queue_update";

    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        try {
            connection = ConnectionUtils.getConnection();
            channel = connection.createChannel();
            //声明交换机：
            channel.exchangeDeclare(DIRECT_EXCHAGE, //交换机名称
                    BuiltinExchangeType.DIRECT //交换机类型，fanout、topic、direct、headers
            );
            //声明队列
            channel.queueDeclare(DIRECT_QUEUE_INSERT, true, false, false, null);
            channel.queueDeclare(DIRECT_QUEUE_UPDATE, true, false, false, null);
            //队列绑定交换机，指定routing key
            channel.queueBind(DIRECT_QUEUE_INSERT, DIRECT_EXCHAGE, "insert");
            channel.queueBind(DIRECT_QUEUE_UPDATE, DIRECT_EXCHAGE, "update");
            //发送信息
            String msg = "新增了商品。路由模式：routing key = insert";
            channel.basicPublish(DIRECT_EXCHAGE, "insert", null, msg.getBytes());
            System.out.println("已发送消息：" + msg);

            //发送信息
            msg = "修改了商品。路由模式：routing key = update";
            channel.basicPublish(DIRECT_EXCHAGE, "update", null, msg.getBytes());
            System.out.println("已发送消息：" + msg);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            ConnectionUtils.close(channel, connection);
        }
    }
}
